package net.sharpf2.api.world;

import net.sharpf2.sfcore.client.Plane;
import net.sharpf2.api.Globals;

/**
 *
 * @author Rick van Biljouw
 */
public class Ground {
    
    /**
     * Returns a tile object for a coordinate
     * @param   x     tile X
     * @param   y     tile Y
     * @param   plane plane tile is on
     * @return  tile
     */
    public static net.sharpf2.sfcore.client.Ground getTile(int x, int y, int plane) {
        Object[][][] objectArray = (Object[][][]) Globals.CONTROLLER.getFieldContainer().getGroup("Static").get("GroundTiles").value(null);
        return new net.sharpf2.sfcore.client.Ground(Globals.METHODS, objectArray[plane][x][y]);
    }

    /**
     * Returns the height of a certain tile
     * @param   x   tile X
     * @param   y   tile Y
     * @return  
     */
    public static int getHeight(int x, int y) {
        int p = Globals.CLIENT.getPlane();

        int x1 = x >> 9;
        int y1 = y >> 9;

        byte[][][] settings = Globals.CLIENT.getGroundSettings();

        if ((settings != null) && (x1 >= 0) && (x1 < 104) && (y1 >= 0) && (y1 < 104)) {
            if ((p <= 3) && ((settings[1][x1][y1] & 2) != 0)) {
                ++p;
            }
            Plane[] planes = Globals.CLIENT.getPlanes();

            if (p < planes.length && planes[p] != null) {
                int[][] heights = planes[p].getHeights();
                if (heights != null) {
                    int x2 = x & 512 - 1;
                    int y2 = y & 512 - 1;
                    int start_h = (heights[x1][y1] * (512 - x2) + heights[x1 + 1][y1] * x2) >> 9;
                    int end_h = (heights[x1][1 + y1] * (512 - x2) + heights[x1 + 1][y1 + 1] * x2) >> 9;
                    return start_h * (512 - y2) + end_h * y2 >> 9;
                }
            }
        }
        return 0;
    }   

}
